#!/bin/env python
#-*- encoding: utf-8 -*-
import os
import csv
import datetime
import time
import math
import xlrd
import sys

def getnvtable(fname,nvdir,outdir,outfname):
	'''
	if len(fname)!=19 or fname[0]!='2':
		return
	'''
	if fname[0:8] != "TRS27080" or len(fname) != 26:
		return
	fdate=fname[0:8]
	fname=nvdir+fname
	sname='?????????'
	wbrd = xlrd.open_workbook(fname) 
	table = wbrd.sheet_by_name(sname.decode('gbk'))
	netasset=table.cell(10,1).value
	curnetvalue=table.cell(7,8).value
	cash=table.cell(15,6).value
	totalprice=table.cell(15,7).value
	totalpnl=table.cell(15,5).value
	curequity=table.cell(15,12).value
	contract=table.cell(15,13).value
	todaypnl=table.cell(15,16).value
	count=table.nrows
	ICmarket=0
	ICprice=0
	ICpnl=0
	ICmargins = 0
	IFmarket=0
	IFprice=0
	IFpnl=0
	IFmargins = 0

	for i in range(18,count):
		amt=table.cell(i,13).value
		iname=table.cell(i,12).value
		if(amt!=0):
			if(iname[0:2]=='IF'):
				IFmarket=table.cell(i,19).value
				IFprice=table.cell(i,16).value
				IFpnl=table.cell(i,18).value
				IFmargins = table.cell(i,15).value
			elif(iname[0:2]=='IC'):
				ICmarket=table.cell(i,19).value
				ICprice=table.cell(i,16).value
				ICpnl=table.cell(i,18).value
				ICmargins = table.cell(i,15).value
	fd=open(outfname,'a')
	fd.write('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (fdate,netasset,curnetvalue,cash,totalprice,totalpnl,curequity,contract,todaypnl,ICmarket,ICprice,ICpnl,ICmargins,IFmarket,IFprice,IFpnl,IFmargins)	)	
	fd.close()

if __name__== '__main__':
#	if len(sys.argv)!=2:
#		print 'please input the production number'
#	else:
	prod = '4'
	curdate =time.strftime("%Y%m%d")
	nvdir='P:\\public\\lhuang\\prod4_netValue\\'
	outdir=nvdir+'\\nvreport\\'
	outfname=outdir+'nvreport'+'.prod'+ prod + '_new.csv'
	fd=open(outfname,'w')
	fd.write('????Date,?????,??????,??????????,??????,?????,??????,???????,???????,IC??????,IC???,IC???????,IC?????,IF??????,IF???,IF???????,IF?????\n')
	fd.close()

	for fname in os.listdir(nvdir):
		getnvtable(fname,nvdir,outdir,outfname)
